package com.globallogic.socialnetwork.util;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

/**
 * Web application bean. Holds usefull method shortcuts for the FacesContext.
 * Also provides services for the jsf backing beans.
 */
@ManagedBean(name = "webApp")
@ApplicationScoped
public class WebApplication {

	public WebApplication() {
	}

	/**
	 * Adds message to the FacesContext to show.
	 * 
	 * @param message
	 *            the message string.
	 */
	public static void addMessage(String message) {
		FacesMessage fm = new FacesMessage(message);
		FacesContext.getCurrentInstance().addMessage(fm.getSummary(), fm);
	}

	/**
	 * Get session attribute by name
	 * 
	 * @param key
	 *            name of session attribute
	 * @return session attribute
	 */
	public static Object getSessionAttribute(String key) {
		FacesContext context = FacesContext.getCurrentInstance();
		return context.getExternalContext().getSessionMap().get(key);
	}

	/**
	 * Set session attribute
	 * 
	 * @param key
	 *            name of session attribute
	 * @param value
	 *            value of session attribute
	 */
	public static void setSessionAttribute(String key, Object value) {
		FacesContext context = FacesContext.getCurrentInstance();
		context.getExternalContext().getSessionMap().put(key, value);
	}

	/**
	 * Check key in request
	 * 
	 * @param key
	 * @return <tt>true</tt> if key is parameter, otherwise <tt>false</tt>
	 */
	public static boolean isParameter(String key) {
		FacesContext context = FacesContext.getCurrentInstance();
		HttpServletRequest request = (HttpServletRequest) context
				.getExternalContext().getRequest();
		return request.getParameter(key) != null;
	}

	/**
	 * Get parameter by name from request
	 * 
	 * @param key
	 * @return parameter
	 */
	public static Object getParameter(String key) {
		FacesContext context = FacesContext.getCurrentInstance();
		HttpServletRequest request = (HttpServletRequest) context
				.getExternalContext().getRequest();
		return request.getParameter(key);
	}

	/**
	 * Invalidate session
	 */
	public static void invalidateSession() {
		FacesContext context = FacesContext.getCurrentInstance();
		context.getExternalContext().invalidateSession();
	}

	/**
	 * Check session contains key
	 * 
	 * @param key
	 * @return <tt>true</tt> if session contains, otherwise <tt>false</tt>
	 */
	public static boolean containsSessionAttribute(String key) {
		FacesContext context = FacesContext.getCurrentInstance();
		return context.getExternalContext().getSessionMap().containsKey(key);
	}
}
